﻿using Nancy;
using Nancy.ModelBinding;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace customer.dao.V2
{
    public class SqlModel
    {   

        public string DB { get; set; }

        public string Sql { get; set; }


    }

    public class SqlModelBinder : IModelBinder
    {

        public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList)
        {
            var queryModel = (instance as SqlModel) ?? new SqlModel();

            System.IO.Stream s = context.Request.Body;
            int count = 0;
            byte[] buffer = new byte[1024];
            StringBuilder builder = new StringBuilder();
            while ((count = s.Read(buffer, 0, 1024)) > 0)
            {
                builder.Append(Encoding.UTF8.GetString(buffer, 0, count));
            }
            s.Flush();
            s.Close();
            s.Dispose();

            string sql = builder.ToString();
            queryModel.Sql = sql;

            var db = context.Request.Headers["DB"].FirstOrDefault();
            if (!string.IsNullOrWhiteSpace(db))
                queryModel.DB = db;

            return queryModel;
        }

        public bool CanBind(Type modelType)
        {
            return modelType == typeof(SqlModel);
        }
    }

}
